const express = require("express");
const cors = require("cors")
const fs = require("./libs/FileHelper");
const db = require("./libs/DBHelper");
const moment = require("moment");
const svgCaptcha = require("svg-captcha");
const { response, request } = require("express");

let server = express();


//验证码
server.get("/yzm", function (request, response, next) {
    const codeConfig = {
        size: 4, // 验证码长度
        ignoreChars: '0oO1ilI', // 验证码字符中排除 0oO1ilI
        noise: (2 + parseInt(Math.random() * 8)), // 干扰线条的数量
        width: 80,
        height: 20,
        fontSize: 20,
        color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
        background: '#eee',
    };
    const captcha = svgCaptcha.create(codeConfig);
    // console.log(captcha);
    captcha.text = captcha.text.toLowerCase();
    response.json(captcha)
})


//静态资源
server.use(express.static("./../src/"))

//支持post请求
server.use(express.urlencoded({ extended: false }));
server.use(express.json());

//拦截器 为了做跨域 CORS
server.use(cors());
// server.all("*", function (request, resposne, next) {
//     resposne.setHeader("content-Type", "application/json;charset=utf-8");
//     resposne.setHeader("Access-Control-Allow-Origin", "*");
//     next()
// })

//post 注册
server.post("/3.reg", async (request, response, next) => {
    let params = [
        request.body.phone,
        request.body.name,
        moment(Date.now()).format("YYYY-MM-DD HH:mm:ss")//获取当地时间
    ]
    let sql = "INSERT INTO `userinfo`(`uPhone`,`uName`,`uDateTime`)VALUES(?,?,?)"
    try {
        let res = await db.exec(sql, params);
        //插入，删除，修改，返回受影响行数，查询返回数据
        let resFlag = (res && res.affectedRows >= 1);
        let oMsg = {
            message: resFlag ? "注册成功" : "注册失败",
            code: resFlag ? 200 : -200,
            date: params
        }
        response.json(oMsg);
    } catch (error) {
        response.json({ message: "注册失败", err: error.message, code: -201 });
    }
})




//post 登录
server.post("/4.login", async function (request, response, next) {
    //1.接受前端发送过来的参数 用户名 密码 手机号
    let params = [
        request.body.phone
    ];
    //2.编写sql语句 不需要显示密码 执行sql语句,带参数
    let sql = "SELECT `uId`, `uPhone` FROM `userinfo` WHERE uPhone=? AND `uStatus`=1;";
    //4.获取结果,进行判断
    try {
        let res = await db.exec(sql, params);
        let flag = (res && res.length >= 1);
        let oMsg = {
            message: flag ? "登录成功" : "登录失败",
            code: flag ? 200 : -200
        }
        flag ? oMsg["data"] = res[0] : "";
        response.json(oMsg);
    } catch (error) {
        response.json({ message: "登录失败", err: error.message, code: 201 });
    }

})

//获取所有的商品
server.get("/prods", async (request, response, next) => {
    let data = JSON.parse(await fs.getFile("./data/production.json"));
    // console.log(data);
    response.json({
        message: "查询成功",
        code: 200,
        data
    })
})


//根据产品id获取产品的详细信息
// 如果路由的路径是 /:id ,要取得id对应的值,使用 param (Vue)
// 动态路由传参
server.get("/prodInfo/:id", async (request, response, next) => {
    let id = request.params.id;
    let data = JSON.parse(await fs.getFile("./data/production.json"));
    let res = data.find(el => el.pid == id);
    // console.log(data);
    response.json({
        msg: "查询成功",
        code: 200,
        data: res
    });
})


//加入购物车 只需要传入用户id和产品名称即可
server.post("/AddCarts", async (request, response, next) => {
    let params = [
        request.body.uId,
        request.body.pname
    ]
    let querySql = "SELECT * FROM `product` WHERE uId=? AND pName=? AND cStatus=1;";
    let res = await db.exec(querySql, params);
    // console.log(res);
    let status = (res && res.length >= 1);//有数据就返回true
    if (status) {
        //修改
        let paramsUpdate = [
            request.body.pnum,
            request.body.uId,
            request.body.pname,
        ]
        let updateSQL = 'UPDATE `product` SET `pNumber`=`pNumber`+? ,pTotal= pNumber*pPrice WHERE uId=? AND pName=? AND cStatus=1;'
        let res = await db.exec(updateSQL, paramsUpdate);
        //更新，删除，修改 返回的是受影响的行数
        let status = (res && res.affectedRows >= 1);
        response.json({
            message: status ? "加入购物车成功u" : "加入失败u",
            code: 200
        })
    } else {
        //插入  "img"  "pname" "pcolor" "psize"  "pprice"  "pnum"
        let params = [
            request.body.uId,
            request.body.img,
            request.body.pname,
            request.body.pcolor,
            request.body.psize,
            request.body.pprice,
            request.body.pnum,
            request.body.pId,
            request.body.pprice * request.body.pnum,//小计
            moment().format("YYYY-MM-DD HH:mm:ss")
        ];
        let insertSQL = "INSERT INTO `product` (`uId`,`pImg`,`pName`,`pColor`,`pSize`,`pPrice`,`pNumber`,`pId`,`pTotal`,`cTime`) VALUES(?,?,?,?,?,?,?,?,?,?);"
        console.log(params);
        let res = await db.exec(insertSQL, params);
        let status = (res && res.affectedRows >= 1);
        response.json({
            message: status ? "加入购物车成功i" : "加入失败i",
            code: 200
        })
    }
})

//查询购物车
server.get("/cartList", async (request, response, next) => {
    let params = [
        request.query.uId
    ]
    let sql = "SELECT *FROM `product` WHERE `cStatus` =1 AND `uId`=?;"
    let res = await db.exec(sql, params);
    response.json({
        messagez: "查询成功",
        data: res
    })
})

//ajax发送 购物车的 cId pnum  修改购物车数量
server.post("/modify", async (request, response, next) => {
    let params = [
        request.body.pnum,
        request.body.cId
    ];
    let sql = "UPDATE `product` SET `pNumber`= ?,`pTotal`=`pNumber`*`pPrice` WHERE `cId`=?;"
    let res = await db.exec(sql, params);
    let status = (res && res.affectedRows >= 1);
    response.json({
        message: status ? "修改数量成功" : "修改数量失败",
        code: 200
    });
})


//删除购物车  post cid 不是真正的删除 数据库中 status变为0
server.post("/delete", async (request, response, next) => {
    let params = [
        request.body.cId
    ]
    let sql = "UPDATE `product` SET `cStatus`=0 WHERE `cId`=?;";
    let res = await db.exec(sql, params);
    console.log(res);
    let status = (res && res.affectedRows >= 1);
    response.json({
        message: status ? "删除成功" : "删除失败",
        code: 200
    })
})



server.listen(8080, () => {
    console.log("服务器启动完毕!");
})